<template>
  <view class="container">
    <!-- 标题栏 -->
    <view class="header">
      <view class="back-button" @click="goBack">
        <uni-icons class="back-icon" custom-prefix="iconfont" type="icon-fanhui" size="18"></uni-icons>
      </view>
      <view class="title">{{ title }}</view>
    </view>
    
    <!-- 视频播放区 -->
    <view class="video-container">
      <video 
        id="videoPlayer"
        :src="videoUrl" 
        class="video-player"
        :poster="videoPoster"
        :controls="true"
        :autoplay="false"
        @timeupdate="onTimeUpdate"
        @ended="onVideoEnded"
      ></video>
    </view>
    
    <!-- 视频信息 -->
    <view class="video-info">
      <view class="video-title">{{ title }}</view>
      <view class="video-meta">
        <text class="meta-item">讲师: {{ lecturer }}</text>
        <text class="meta-item">时长: {{ duration }}</text>
        <text class="meta-item">发布日期: {{ publishDate }}</text>
      </view>
      <view class="video-desc">{{ description }}</view>
    </view>
    
    <!-- 章节列表 -->
    <view class="chapters-container">
      <view class="section-title">课程章节</view>
      <view class="chapter-list">
        <view 
          v-for="(chapter, index) in chapters" 
          :key="index"
          class="chapter-item"
          :class="{ 'active': currentChapter === index }"
          @click="switchChapter(index)"
        >
          <view class="chapter-title">{{ chapter.title }}</view>
          <view class="chapter-duration">{{ chapter.duration }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 获取页面传递的参数
const title = ref('视频标题')
const contentId = ref('')
const parentId = ref('')

// 视频数据
const videoUrl = ref('')
const videoPoster = ref('/static/images/video-poster.jpg')
const lecturer = ref('未知')
const duration = ref('00:00')
const publishDate = ref('--')
const description = ref('暂无描述')
const chapters = ref([])
const currentChapter = ref(0)
const lastPlayPosition = ref(0)

// 视频播放器实例
let videoContext = null

// 初始化
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.$page.options
  
  if (options) {
    contentId.value = options.id || ''
    title.value = decodeURIComponent(options.title || '视频详情')
    parentId.value = options.parentId || ''
    
    // 获取视频数据
    fetchVideoData(contentId.value)
  }
  
  // 创建视频上下文
  videoContext = uni.createVideoContext('videoPlayer')
  
  // 恢复上次播放位置
  getLastPlayPosition()
})

// 组件卸载时保存播放位置
onUnmounted(() => {
  savePlayPosition()
})

// 获取视频数据
const fetchVideoData = async (id) => {
  try {
    // 模拟API请求
    // const response = await uni.request({
    //   url: `your-api-endpoint/videos/${id}`,
    //   method: 'GET'
    // })
    
    // 模拟数据
    
  } catch (error) {
    console.error('Failed to fetch video data:', error)
    uni.showToast({
      title: '获取视频内容失败',
      icon: 'none'
    })
  }
}

// 切换章节
const switchChapter = (index) => {
  if (index >= 0 && index < chapters.value.length && videoContext) {
    currentChapter.value = index
    const startTime = chapters.value[index].startTime
    videoContext.seek(startTime)
    videoContext.play()
  }
}

// 视频播放进度更新
const onTimeUpdate = (e) => {
  const currentTime = e.detail.currentTime
  lastPlayPosition.value = currentTime
  
  // 更新当前章节
  for (let i = chapters.value.length - 1; i >= 0; i--) {
    if (currentTime >= chapters.value[i].startTime) {
      currentChapter.value = i
      break
    }
  }
}

// 视频播放结束
const onVideoEnded = () => {
  // 可以在这里记录视频完成状态
  updateVideoProgress(100)
  lastPlayPosition.value = 0
}

// 获取上次播放位置
const getLastPlayPosition = async () => {
  try {
    // 模拟从本地存储获取
    // const position = uni.getStorageSync(`video_position_${contentId.value}`)
    // if (position && videoContext) {
    //   lastPlayPosition.value = position
    //   videoContext.seek(position)
    // }
  } catch (error) {
    console.error('Failed to get last play position:', error)
  }
}

// 保存播放位置
const savePlayPosition = async () => {
  try {
    // 模拟保存到本地存储
    // uni.setStorageSync(`video_position_${contentId.value}`, lastPlayPosition.value)
    
    // 同时更新到服务器
    updateVideoProgress(Math.floor((lastPlayPosition.value / getTotalDuration()) * 100))
  } catch (error) {
    console.error('Failed to save play position:', error)
  }
}

// 获取视频总时长（秒）
const getTotalDuration = () => {
  if (chapters.value.length === 0) return 0
  const lastChapter = chapters.value[chapters.value.length - 1]
  return lastChapter.startTime + convertDurationToSeconds(lastChapter.duration)
}

// 将时长格式(MM:SS)转换为秒
const convertDurationToSeconds = (duration) => {
  const parts = duration.split(':')
  return parseInt(parts[0]) * 60 + parseInt(parts[1])
}

// 更新观看进度到服务器
const updateVideoProgress = async (percentage) => {
  try {
    // 模拟API请求
    // await uni.request({
    //   url: 'your-api-endpoint/video-progress',
    //   method: 'POST',
    //   data: {
    //     contentId: contentId.value,
    //     position: lastPlayPosition.value,
    //     percentage: percentage,
    //     timestamp: new Date().getTime()
    //   }
    // })
    console.log('Video progress updated:', percentage + '%')
  } catch (error) {
    console.error('Failed to update video progress:', error)
  }
}

// 返回上一页
const goBack = () => {
  savePlayPosition()
  uni.navigateBack()
}
</script>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-top: var(--status-bar-height);
  background-color: #f5f5f5;
}

.header {
  height: 90rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  background-color: #ffffff;
  border-bottom: 2rpx solid rgba(229, 229, 229, 1);
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  margin-left: 20rpx;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.video-container {
  margin: 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.video-player {
  width: 100%;
  height: 422rpx;
}

.video-info {
  margin: 0 20rpx;
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.video-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.video-meta {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
}

.meta-item {
  font-size: 28rpx;
  color: #666;
  margin-right: 30rpx;
  margin-bottom: 10rpx;
}

.video-desc {
  font-size: 30rpx;
  line-height: 1.6;
  color: #333;
}

.chapters-container {
  margin: 20rpx;
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.chapter-list {
  max-height: 600rpx;
  overflow-y: auto;
}

.chapter-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid rgba(229, 229, 229, 0.6);
  
  &:last-child {
    border-bottom: none;
  }
  
  &.active {
    color: #2A82E4;
  }
}

.chapter-title {
  font-size: 28rpx;
  flex: 1;
}

.chapter-duration {
  font-size: 24rpx;
  color: #999;
  margin-left: 20rpx;
}
</style> 